var router=require('express').Router();
var Note=require('../models/note');
var Page=require('../models/page');

module.exports=router;

router.get('/',(req,res,next)=>{
    Note.get(req.query,(err,ret,page,cbQuery)=>{
        if(err)return next(err);
        var {start,end}=req.query;
        var status={
            ygq:-1==req.query.status,
            wwc:0==req.query.status,
            ywc:1==req.query.status,
        };
        var actions={
            '-1':[{txt:'删除',action:'del'}],
            '0':[{txt:'完成',action:'finish'},{txt:'删除',action:'del'}],
            '1':[{txt:'删除',action:'del'}]
        };
        var notes=ret.map(note=>{
            note.actions=actions[note.status];
            return note;
        });

        console.log('page:',page);
        console.log('cbQuery:',cbQuery);

        res.render('edit',{
                title:'Edit',
                notes:notes,
                query:{start,end,status},
                page:new Page({
                    url:'/edit',
                    page:Object.assign({
                        prev:page.curr-1,
                        next:page.curr+1
                    },page),
                    query:cbQuery
                })
            }
        );
    });
});

router.get('/finish',(req,res,next)=>{
    var id=req.query.id;
    Note.update({_id:id},{status:1},(err)=>{
        if(err)return next(err);
        res.redirect('back');
    });
});

router.get('/del',(req,res,next)=>{
    var id=req.query.id;
    Note.remove({_id:id},(err)=>{
        if(err)return next(err);
        res.redirect('back');
    });
});